import React, { ReactNode, useCallback, useEffect, useState } from 'react';
import { IParamModelLiteData, ISelectParamForm } from '@manycore/pages-vm-api';
import { FormField } from '../form-field';
import 'antd/es/collapse/style/css';
import Collapse from 'antd/es/collapse';

const { Panel } = Collapse;

export interface IFormChildren {
  groupName: string;
  children: ReactNode;
}

export interface IFormProps {
  form: Array<ISelectParamForm | IFormChildren>;
  onChange?: (field: IParamModelLiteData, value: string | number | any) => void;
}

export function Form(props: IFormProps) {
  const { form, onChange = (...args: any[]) => {} } = props;

  const [defaultActiveKeys, setDefaultActiveKeys] = useState<string[]>(form.map((i) => i.groupName));

  const onPanelArrowClick = useCallback(
    function (keys: string[]) {
      setDefaultActiveKeys(keys);
    },
    [defaultActiveKeys]
  );

  useEffect(() => {
    setDefaultActiveKeys(form.map((i) => i.groupName));
  }, [form]);

  return (
    <Collapse className="collapse-demo" activeKey={defaultActiveKeys} onChange={onPanelArrowClick}>
      {form.map((f) => {
        return (
          <Panel key={f.groupName} header={f.groupName}>
            {(f as ISelectParamForm).fields &&
              (f as ISelectParamForm).fields.map((field) => {
                return <FormField field={field} onChange={(value) => onChange(field, value)} />;
              })}
            {(f as IFormChildren).children || null}
          </Panel>
        );
      })}
    </Collapse>
  );
}
